﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using System;
using System.Collections.Generic;
using System.Linq;
using IOA.MES.Common;

namespace IOA.MES.Business
{
    /// <summary>
    /// 订单管理（错误代码：117001）
    /// </summary>
    public class OrderMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="model">订单对象</param>
        public void EditOrder(VOrder model)
        {
            if (model.PkId <= 0)
            {
                var entity = mesDb.Orders.FirstOrDefault(_ => _.InnerOrderNo == model.InnerOrderNo && _.Valid);
                if (entity != null)
                {
                    throw new MultiLanBizException(117001, model.InnerOrderNo);// $"订单号{model.OrderNo}已存在");
                }
                if (entity == null)
                {
                    entity = Mapper.Map<Order>(model);
                    entity.CreateTime = DateTime.Now;
                    mesDb.Orders.Add(entity);
                    mesDb.SaveChanges();

                    new ViaSiteConfigMgr().ResetOrderConfig(new VViaSiteConfig { OrderNo = entity.InnerOrderNo, CreateBy = entity.CreateBy });
                }
            }
            else
            {
                var entity = mesDb.Orders.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(117002);// $"订单不存在或已被删除，无法修改");
                }
                var exist = mesDb.Orders.FirstOrDefault(_ => _.InnerOrderNo == model.InnerOrderNo && _.PkId != model.PkId && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(117003, model.InnerOrderNo);// $"订单号{model.OrderNo}已存在，请修改其他订单号");
                }
                entity.ContractNo = model.ContractNo;
                entity.OrderTime = model.OrderTime;
                entity.CustomerCode = model.CustomerCode;
                entity.CustomerName = model.CustomerName;
                entity.ProductNum = model.ProductNum;
                entity.Description = model.Description;
                entity.Remark = model.Remark;
                mesDb.SaveChanges();
            }
        }

        /// <summary>
        /// 获取订单
        /// </summary>
        /// <param name="orderId">订单ID</param>
        public VOrder GetOrder(int orderId)
        {
            var entity = mesDb.Orders.FirstOrDefault(_ => _.PkId == orderId && _.Valid);
            return Mapper.Map<VOrder>(entity);
        }

        /// <summary>
        /// 获取订单
        /// </summary>
        /// <param name="innerOrderNo">订单号</param>
        public VOrder GetOrder(string innerOrderNo)
        {
            var entity = mesDb.Orders.FirstOrDefault(_ => _.InnerOrderNo == innerOrderNo && _.Valid);
            var model = Mapper.Map<VOrder>(entity);
            return model;
        }

        /// <summary>
        /// 查询订单列表
        /// </summary>
        public List<VOrder> QueryOrders()
        {
            var query = mesDb.Orders.AsNoTracking().Where(_ => _.Valid);

            var entities = query.OrderByDescending(_ => _.PkId).OrderByDescending(_ => _.PkId).ToList();
            var models = Mapper.Map<List<VOrder>>(entities);

            return models;
        }

        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">全部数量</param>
        /// <param name="innerOrderNo">订单号</param>
        /// <param name="customer">客户信息</param>
        /// <param name="startDate">下单开始日期</param>
        /// <param name="endDate">下单截止日期</param>
        /// <returns>订单列表</returns>
        public List<VOrder> QueryOrders(int pageIndex, int pageSize, out int total, string innerOrderNo, string customer, OrderStatus? status, DateTime? startDate, DateTime? endDate)
        {
            var query = mesDb.Orders.Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(innerOrderNo))
            {
                query = query.Where(_ => _.InnerOrderNo.Contains(innerOrderNo));
            }
            if (!string.IsNullOrWhiteSpace(customer))
            {
                query = query.Where(_ => _.CustomerCode.Contains(customer) || _.CustomerName.Contains(customer));
            }
            if (startDate.HasValue)
            {
                query = query.Where(_ => _.OrderTime >= startDate.Value);
            }
            if (endDate.HasValue)
            {
                var endTime = endDate.Value.AddDays(1);
                query = query.Where(_ => _.OrderTime < endTime);
            }
            if (status.HasValue)
            {
                query = query.Where(_ => _.Status == status.Value);
            }

            total = query.Count();
            var entities = query.OrderByDescending(_ => _.PkId).Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(_ => _.PkId).ToList();
            var models = Mapper.Map<List<VOrder>>(entities);
            return models;
        }

        /// <summary>
        /// 查询订单产品列表
        /// </summary>
        /// <param name="innerOrderNo">订单号</param>
        /// <returns>产品列表</returns>
        public List<VOrderProduct> QueryOrderProducts(string innerOrderNo)
        {
            var entities = mesDb.OrderProducts.Where(_ => _.InnerOrderNo == innerOrderNo && _.Valid).ToList();
            return Mapper.Map<List<VOrderProduct>>(entities);
        }
    }
}
